package top.maohh.study.demo.zookeeper;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.List;

import static top.maohh.study.demo.zookeeper.config.ZookeeperConfig.ZK_ADDRESS;
import static top.maohh.study.demo.zookeeper.config.ZookeeperConfig.ZK_GROUP_NAME;

/**
 * 分组列表
 *
 * @author maohh
 */
public class ListGroup extends ConnectionWatcher {
    private static Stat stat = new Stat();

    /**
     * 获取一个分组的所有子节点
     *
     * @param groupName
     * @throws KeeperException
     * @throws InterruptedException
     */
    public void list(String groupName) throws KeeperException,
            InterruptedException {
        String path = "/" + groupName;
        try {
            List<String> children = zk.getChildren(path, true);
            if (children.isEmpty()) {
                System.out.printf("No members in group %s\n", groupName);
                System.exit(1);
            }
            for (String child : children) {
                System.out.println(child);
            }
        } catch (KeeperException.NoNodeException e) {
            System.out.printf("Group %s does not exist\n", groupName);
            System.exit(1);
        }
    }

    public static void main(String[] args) throws Exception {
//        String hosts = ZK_ADDRESS;
        ListGroup listGroup = new ListGroup();
        listGroup.connect(ZK_ADDRESS);
        listGroup.list(ZK_GROUP_NAME);
        listGroup.close();
    }
}